/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.gwxs;

import static cn.ac.iie.di.global.GlobalParas.CONT;
import cn.ac.iie.di.ipparser.RangeSearch;
import cn.ac.iie.di.tools.GetIpTools;
import cn.ac.iie.di.tools.UnicodeUtils;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.FileUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

/**
 *
 * @author Austin
 */
public class test {

    public static HashMap<String, Integer> id2Provinces = new HashMap();

    public static void main(String[] args) throws JSONException {
        String ooo = "[\"{\\\"aeskey\\\":\\\"ef2eabdbf9b041ec83a0045c9f8316bc\",\"fileid\\\":\\\"30500201000449304702010002048124f68b02030f53ed02041100000a02045978bdb50425617570696d675f363663653334353661363865653365315f313530313038353130393930350201000201000400\\\"}\"]".replace("[\"", "").replace("\"]", "").replaceAll("\\\"", "\"");
        System.out.println();
        JSONObject j = new JSONObject(ooo);
        System.out.println(j.length());

//        1496977200=38, 1496991600=71, 1496995200=194, 1496988000=452, 1496984400=236, 1496883600=9
        Map<Long, Integer> map = new HashMap<Long, Integer>();
        map.put(1496977200L, 38);
        map.put(1496991600L, 71);
        map.put(1496995200L, 194);
        map.put(1496988000L, 452);
        map.put(1496984400L, 236);
        Set<Long> keys = map.keySet();
        Iterator<Long> ite = keys.iterator();
        while (ite.hasNext()) {
            Long key = ite.next();
            Integer value = map.get(key);
            System.out.println(key + "=" + value);
//            session.setString("key", key);
//            session.setLong("value", value);
//                        jedis.incrBy(key, value);
        }
        System.out.println("");

//
//        FileUtils.deleteQuietly(new File("C:\\Users\\Austin\\Desktop\\new 3.txt"));
//
//        String xml = "<msg><voicemsg   endflag=\"2\" length=\"3883\" voicelength=\"2120\" clientmsgid=\"\" fromusername=\"wxid_6369213168712\" downcount=\"0\" cancelflag=\"0\" voiceformat=\"4\" forwardflag=\"0\" bufid=\"290516501902589954\"/></msg>";
//        try {
////            Document document = DocumentHelper.parseText(xml);
////            Element rootElement = document.getRootElement();
////            System.out.println(rootElement.getName());
////            for (Iterator iter = rootElement.elementIterator(); iter.hasNext();) {
////                Element element = (Element) iter.next(); // 获取标签对象
////                System.out.println(element.getName());
////                // 获取该标签对象的属性
////                List<Attribute> xx = element.attributes();
////                for (Attribute x : xx) {
////                    System.out.println(x.getName());
////                    System.out.println(x.getValue());
////                }
////            }
//            String[] feature = null;
//            Document d = DocumentHelper.parseText(xml);
//            Element rootElement = d.getRootElement();
//            List<Element> l = rootElement.elements();
//            for (Element e : l) {
//                List<Attribute> attrs = e.attributes();
//                feature = new String[attrs.size()];
//                for (int i = 0; i < attrs.size(); i++) {
//                    feature[i] = attrs.get(i).getText();
//                }
//            }
//            if (feature == null) {
//                System.out.println("xxxxxxxxxxxx" + new String[0].toString());
////                session.setStrings("m_mm_feature", new String[0]);
//            } else {
//                System.out.println("oooooooooooo" + feature.toString());
////                session.setStrings("m_mm_feature", feature);
//            }
//            System.out.println("");
////            Element elementOption = (Element) iterInner.next();
//        } catch (DocumentException ex) {
//            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        System.out.println(GetIpTools.getIpAddr("59.67.195.255"));
        try {
//            new FileInputStream(ClassLoader.getSystemClassLoader().getResource("ip2province").getFile());
            readId2Province();
            RangeSearch rs1 = null;
            try {
//            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(ClassLoader.getSystemClassLoader().getResource("IPGeoLocator.dat").getFile()));
//            byte c[] = new byte[1024];
//            int n = 0;
//            while ((n = bis.read(c)) != -1) {
//                String temp = new String(c, 0, n,"UTF-8");
//                System.out.println(temp);
//            }
                ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(ClassLoader.getSystemClassLoader().getResource("IPGeoLocator.dat").getFile())));
                rs1 = (RangeSearch) in.readObject();
            } catch (IOException ex) {
                System.out.println(ex);
                System.exit(0);
            } catch (ClassNotFoundException ex) {
                System.out.println(ex);
                System.exit(0);
            }
            long t1 = System.currentTimeMillis();
            String province = rs1.getValue(ipToNumber("59.42.97.129"), "district");
            String country = rs1.getValue(ipToNumber("59.42.97.129"), "country");
            int[] addrNum = new int[2];
            if (province == null || "".equals(province.trim()) || "00".equals(province.trim())) {
//                        log.warn(" get " + sendIp + " fail from locator  00 , and the country is " + GlobalParas.rs1.getValue(sendIp, "country") + " ip is " + sendIp);
                if (id2Provinces.containsKey(country)) {
                    addrNum[0] = id2Provinces.get(country);
                    if (id2Provinces.get(country).toString().length() < 4) {
                        addrNum[1] = Integer.parseInt(id2Provinces.get(country).toString());
                    } else {
                        addrNum[1] = Integer.parseInt(id2Provinces.get(country).toString().substring(0, 2));
                    }
                } else {
                    addrNum[0] = -1;
                    addrNum[1] = -1;
                }
            } else if (id2Provinces.containsKey(province.trim())) {
                int pro = id2Provinces.get(province.trim());
                addrNum[0] = pro;
                addrNum[1] = Integer.parseInt(String.valueOf(pro).substring(0, 2));
            } else if (province.trim().endsWith("0")) {
//                        log.warn(province.trim());
                if (id2Provinces.containsKey(province.trim().split("[0]")[0])) {
                    int pro = id2Provinces.get(province.trim().split("[0]")[0]);
                    addrNum[0] = pro;
                    addrNum[1] = Integer.parseInt(String.valueOf(pro).substring(0, 2));
                } else if (id2Provinces.containsKey(country)) {
                    addrNum[0] = id2Provinces.get(country);
                    addrNum[1] = Integer.parseInt(id2Provinces.get(country).toString().substring(0, 2));
                } else {
                    addrNum[0] = -1;
                    addrNum[1] = -1;
                }

            } else {
                if (!"IANA".equals(country)) {
//                    logger.warn("get " + ip + " fail from locator , and the country is " + country + " , the province is " + province);
                }
                addrNum[0] = -1;
                addrNum[1] = -1;
//                        log.error("msg get null wb_nad : " + province);
            }
            System.out.println(addrNum[0]);
            System.out.println(addrNum[1]);
            int dom = 0;
            if (addrNum[1] < 1000 && addrNum[1] > 100) {
                dom = -1;
                System.out.println("m_country_code=" + addrNum[1]);
                System.out.println("u_loc_county=-1");
                System.out.println("u_loc_province=-1");
//                            logger.info("ipipipipip" + addrNum[1] + msg.element("ClientIP").getText());
            } else {
                dom = 1;
                System.out.println("m_country_code=" + 150);
                System.out.println("u_loc_county=" + addrNum[0]);
                System.out.println("u_loc_province=" + addrNum[1]);
            }
            System.out.println(System.currentTimeMillis() - t1);
        } catch (Exception ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public static void readId2Province() throws IOException {
//        BufferedReader br = new BufferedReader(new FileReader(ClassLoader.getSystemClassLoader().getResource("log4j.properties").getFile()));
        BufferedReader br = null;
        try {
            File file = new File(ClassLoader.getSystemClassLoader().getResource("ip2province").getFile());
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                String[] id2Province = line.split("[|]");
                id2Provinces.put(id2Province[0].trim(), Integer.parseInt(id2Province[1].trim()));
            }
        } catch (Exception e) {
            System.out.println(e);
            System.exit(0);
        } finally {
            br.close();
        }
    }

    private static Long ipToNumber(String ip) {
        Long ips = 0L;
        String[] numbers = ip.split("\\.");
        //等价上面  
        for (int i = 0; i < 4; ++i) {
            ips = ips << 8 | Integer.parseInt(numbers[i]);
        }
        return ips;
    }
}
